package com.jckj.core.controller;

/**
 * Copyright &copy; 2018-2018 <a href="#">聚成科技</a> All rights reserved.
 */

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jckj.core.entity.*;
import com.jckj.core.enums.NotifyType;
import com.jckj.core.service.*;
import com.jckj.core.util.StringUtils;
import com.jckj.core.validator.groups.Add;
import com.jckj.core.validator.groups.Delete;
import com.jckj.core.validator.groups.Edit;
import com.jckj.core.validator.groups.View;
import com.jckj.core.vos.LoginUserVo;
import com.jckj.core.vos.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.List;

/**
 * 通知公告的控制器
 *
 * @author :liukuan
 * @date :2018-01-26
 */
@Controller
@RequestMapping("/admin/notify")
public class NotifyController {

    @Autowired
    private NotifyService notifyService;
    @Autowired
    private NotifyAttachmentService notifyAttachmentService;
    @Autowired
    private UserService userService;
    @Autowired
    private ParkNotifyService parkNotifyService;
    @Autowired
    private UserNotifyService userNotifyService;
    @Autowired
    private NotifyUserViewService notifyUserViewService;
    @Autowired
    private NotifyFarmViewService notifyFarmViewService;
    @Autowired
    private NotifySysUserViewService notifySysUserViewService;
    @Autowired
    private NotifyAttachmentViewService notifyAttachmentViewService;

    @Autowired
    private ParkService parkService;

    @Autowired
    private LoginUserVo loginUserVo;

    /**
     * 使用通配符的方法，根据url地址跳转到相应的视图页面
     * 时间：2018-01-26 15:48
     * author:刘宽
     */
    @RequestMapping(value = "/{page}", method = RequestMethod.GET)
    public String notifyView(@PathVariable String page,
                             @RequestParam(required = false) String id,
                             @RequestParam(required = false) String type,
                             HttpServletRequest request) {
        if (StringUtils.isNotBlank(id)) {
            request.setAttribute("id", id);
            if(StringUtils.isNotBlank(type)){
                request.setAttribute("type",type);
            }
        }
        return page;
    }

    /**
     * 查询的方法并且带分页
     * 时间：2018-01-23 17:07
     * @param pageNum
     * @param pageSize
     * @return
     * @author:刘宽
     */
    @RequestMapping(value = "/selectNotifyByPage", method = RequestMethod.POST)
    @ResponseBody
    public Result selectNotifyByPageHelper(@RequestParam(required = true, defaultValue = "1") Integer pageNum,
                                           @RequestParam(required = false) Integer pageSize) {
        List<NotifyUserView> list = notifyUserViewService.findUserId(loginUserVo.getId());
        Notify notify=new Notify();
        notify.setType(list.get(0).getType());
        PageHelper.startPage(pageNum,pageSize);
        if(NotifyType.OUTER.getCode().equals(list.get(0).getType())){
            List<NotifyFarmView> list1 = notifyFarmViewService.findByNotify(notify);
            PageInfo<NotifyFarmView>  pageInfo=new PageInfo<>(list1);
            return Result.ok(pageInfo);
        }else{
            List<NotifySysUserView> list2 = notifySysUserViewService.findByNotify(notify);
            PageInfo<NotifySysUserView>  pageInfo=new PageInfo<>(list2);
            return Result.ok(pageInfo);
        }
    }

    /**
     * 查询的方法并且带分页
     * 时间：2018-02-10
     * @param pageNum
     * @param pageSize
     * @return
     * @author:刘宽
     */
    @RequestMapping(value = "/findAll", method = RequestMethod.POST)
    @ResponseBody
    public Result selectNotifyByPageHelper(@RequestParam(required = true) String status,
                                           @RequestParam(required = true, defaultValue = "1") Integer pageNum,
                                           @RequestParam(required = false,defaultValue = "4") Integer pageSize){
        PageInfo<Notify> pageInfo = notifyService.findAll(status, pageNum, pageSize);
        if(pageInfo.getList().size()>0){
            return Result.ok(pageInfo);
        }
        return Result.error("服务器错误");
    }

    /**
     * 进入详情页把状态改成已读状态
     * @param id
     * @param mv
     * @return
     */
    @RequestMapping(value = "/readflag", method = RequestMethod.GET)
    public ModelAndView readflag(@RequestParam(required = true) String id,ModelAndView mv){
            NotifyUserView notifyUserView = notifyUserViewService.findById(id);
            if(notifyUserView!=null){
                if(NotifyType.OUTER.getCode().equals(notifyUserView.getType())){
                    ParkNotify parkNotify=new ParkNotify();
                    parkNotify.setReadFlag(true);
                    parkNotify.setReadTime(Calendar.getInstance().getTime());
                    parkNotify.setReadBy(notifyUserView.getUserId());
                    parkNotifyService.updateByNotifyId(parkNotify,id);
                }else{
                    UserNotify userNotify=new UserNotify();
                    userNotify.setReadFlag(true);
                    userNotify.setReadTime(Calendar.getInstance().getTime());
                    userNotifyService.updateByNotifyId(userNotify,id);
                }

                List<NotifyAttachmentView> notifyAttachmentViewList = notifyAttachmentViewService.findById(id);
                mv.addObject("notifyAttachmentViewList",notifyAttachmentViewList);
                mv.addObject("notifyUserView",notifyUserView);
                mv.setViewName("notifyRead");
            }else{
                mv.setViewName("404");
            }

            return mv;
    }

    /**
     * 选择相应的类型查出相应的对象
     * 时间：2018-01-24 17:07
     *
     * @author:刘宽
     */
    @RequestMapping(value = "/selectByType", method = RequestMethod.POST)
    @ResponseBody
    public Result selectByType(@ModelAttribute @Validated(value = View.class) Notify notify,
                               BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.invalidParams(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        if (NotifyType.OUTER.getCode().equals(notify.getType())) {
            List<FarmPark> farmParkList = parkService.findAll();
            return Result.ok(farmParkList);
        } else {
            List<SysUser> userList = userService.findOfficeWorker();
            return Result.ok(userList);
        }
    }

    /**
     * 添加的方法
     * 时间：2018-01-23 17:07
     * @author:刘宽 attachmentIds:是一个附件表的一个字符串以逗号分隔
     * publishIds:发布对象的字符串,以逗号分隔
     */
    @RequestMapping(value = "/notifyInsert", method = RequestMethod.POST)
    @ResponseBody
    public Result insertNotify(@ModelAttribute @Validated(value = Add.class) Notify notify,
                               BindingResult bindingResult,
                               String attachmentIds,
                               @RequestParam(name = "publishIds[]") List<String>  publishIds) {

        if (bindingResult.hasErrors()) {
            return Result.invalidParams(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }

        notify.setId(StringUtils.genId());
        notify.setStatus("0");
        notify.setCreateBy(loginUserVo.getId() == null ? null : loginUserVo.getId());
        notify.setCreateTime(Calendar.getInstance().getTime());
        int num = notifyService.insertConditionNotify(notify);
        if (num > 0) {
            //如果是外部园区的话
            if (NotifyType.OUTER.getCode().equals(notify.getType())) {
                for (int i = 0; i < publishIds.size(); i++) {
                    ParkNotify pn = new ParkNotify();
                    pn.setId(StringUtils.genId());
                    pn.setNotifyId(notify.getId());
                    pn.setParkId(publishIds.get(i));
                    pn.setCreateTime(Calendar.getInstance().getTime());
                    pn.setCreateBy(notify.getCreateBy());
                    pn.setReadFlag(false);
                    parkNotifyService.insert(pn);
                }
            } else {
                //如果是内部科室的话
                for (int i = 0; i < publishIds.size(); i++) {
                    UserNotify un = new UserNotify();
                    un.setId(StringUtils.genId());
                    un.setNotifyId(notify.getId());
                    un.setUserId(publishIds.get(i));
                    un.setCreateTime(Calendar.getInstance().getTime());
                    un.setCreateBy(notify.getCreateBy());
                    un.setReadFlag(false);
                    userNotifyService.insert(un);
                }

            }
            //附件的信息
            String[] attids = attachmentIds.split(",");
            for (int j = 0; j < attids.length; j++) {
                NotityAttachementKey nak = new NotityAttachementKey();
                nak.setNotifyId(notify.getId());
                nak.setAttachmentId(attids[j]);
                notifyAttachmentService.insertNotifyAttachment(nak);
            }
            return Result.ok();
        }
        return Result.error("执行错误");
    }

    /**
     * 修改的控制器
     * 时间：2018-01-23 17:08
     * @author:刘宽
     */
    @RequestMapping(value = "/notifyUpdate", method = RequestMethod.POST)
    @ResponseBody
    public Result updateNotify(@ModelAttribute @Validated(value = Edit.class) Notify notify,
                               BindingResult bindingResult,
                               String attachmentIds,
                               @RequestParam(name = "publishIds[]") List<String> publishIds,
                               String typechoose) {
        if (bindingResult.hasErrors()) {
            return Result.invalidParams(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }

        //根据id删除所对应表中数据
        if(NotifyType.OUTER.getCode().equals(notify.getType())){
            parkNotifyService.deleteByNotifyId(notify.getId());
        }else{
            userNotifyService.deleteByNotifyId(notify.getId());
        }
        notifyAttachmentService.deleteByNotifyId(notify.getId());


        notify.setStatus("0");
        notify.setUpdateBy(loginUserVo.getId() == null ? null : loginUserVo.getId());
        notify.setUpadteTime(Calendar.getInstance().getTime());
        int num = notifyService.updateConditionNotify(notify);
        if (num > 0) {
                    //如果是外部园区的话
                if (NotifyType.OUTER.getCode().equals(typechoose)) {
                    for (int i = 0; i < publishIds.size(); i++) {
                        ParkNotify pn = new ParkNotify();
                        pn.setId(StringUtils.genId());
                        pn.setNotifyId(notify.getId());
                        pn.setParkId(publishIds.get(i));
                        pn.setCreateTime(Calendar.getInstance().getTime());
                        pn.setCreateBy(loginUserVo.getId() == null ? null : loginUserVo.getId());
                        pn.setReadFlag(false);
                        parkNotifyService.insert(pn);
                    }
                } else {
                    for (int i = 0; i < publishIds.size(); i++) {
                        //如果是内部科室的话
                        UserNotify un = new UserNotify();
                        un.setId(StringUtils.genId());
                        un.setNotifyId(notify.getId());
                        un.setUserId(publishIds.get(i));
                        un.setCreateTime(Calendar.getInstance().getTime());
                        un.setCreateBy(loginUserVo.getId() == null ? null : loginUserVo.getId());
                        un.setReadFlag(false);
                        userNotifyService.insert(un);
                    }
                }

                      //附件的信息
            String[] attids = attachmentIds.split(",");
            for (int j = 0; j < attids.length; j++) {
                NotityAttachementKey nak = new NotityAttachementKey();
                nak.setNotifyId(notify.getId());
                nak.setAttachmentId(attids[j]);
                notifyAttachmentService.insertNotifyAttachment(nak);
            }
            return Result.ok();
        }
        return Result.error("执行错误");
    }

    /**
     * 删除的控制器
     * 时间：2018-01-25 11:33
     *
     * @author:刘宽
     * @param notify
     */
    @RequestMapping(value = "/notifyDelete", method = RequestMethod.POST)
    @ResponseBody
    public Result deleteNotify(@ModelAttribute @Validated(value = Delete.class) Notify notify,
                               BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return Result.invalidParams(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        Notify n = notifyService.findNotifyByPrimaryKey(notify.getId());
        if (n != null) {
            if (NotifyType.OUTER.getCode().equals(n.getType())) {
                parkNotifyService.deleteByNotifyId(n.getId());
            } else {
                userNotifyService.deleteByNotifyId(n.getId());
            }
            notifyAttachmentService.deleteByNotifyId(n.getId());
            notifyService.deleteConditionNotify(n.getId());
            return Result.ok();
        }
        return Result.error("执行错误");
    }

    /**
     * 下发公告的方法，根据下发的人的id查数据库并做相应的处理
     * @author:liukuan id:为通知公告的id
     */
    @RequestMapping(value = "publish", method = RequestMethod.POST)
    @ResponseBody
    public Result issuedNotify(@ModelAttribute @Validated(value = Edit.class) Notify notify,
                               BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return Result.invalidParams(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        notify.setStatus("1");
        notify.setSendBy(loginUserVo.getId() == null ? null : loginUserVo.getId());
        notify.setSendTime(Calendar.getInstance().getTime());
        int num = notifyService.updateConditionNotify(notify);
        if (num > 0) {
            return Result.ok();
        }
        return Result.error("执行错误");

    }

    /**
     * 根据主键查询园区及附件表中的相关的信息
     */
    @RequestMapping(value = "/find", method = RequestMethod.GET)
    public ModelAndView find(@RequestParam(value = "id",required = true) String id,
                             ModelAndView mv) {
        NotifyUserView notifyUserView = notifyUserViewService.findById(id);
        if(notifyUserView != null){
            Notify notify=new Notify();
            notify.setId(id);
            if(NotifyType.OUTER.getCode().equals(notifyUserView.getType())){
                List<NotifyFarmView> notifyFarmViewList = notifyFarmViewService.findByNotify(notify);
                mv.addObject("notifyfarmList",notifyFarmViewList);
            }else{
                List<NotifySysUserView> notifySysUserViewList = notifySysUserViewService.findByNotify(notify);
                mv.addObject("notifySysUserViewList",notifySysUserViewList);
            }
            List<NotifyAttachmentView> notifyAttachmentViewList = notifyAttachmentViewService.findById(id);
            mv.addObject("notifyAttachmentViewList",notifyAttachmentViewList);
            mv.addObject("notifyUserView",notifyUserView);
            mv.setViewName("notifyDetail");
        }else{
            mv.setViewName("404");
        }

           return mv;
    }

    /**
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/findById",method = RequestMethod.GET)
    public ModelAndView findById(@RequestParam(value = "id", required = true) String id,ModelAndView mv){
        Notify notify = notifyService.findNotifyByPrimaryKey(id);
        if(notify!=null){
            if(NotifyType.OUTER.getCode().equals(notify.getType())){
                List<NotifyFarmView> farmList = notifyFarmViewService.findByNotify(notify);
                mv.addObject("farmList",farmList);
            }else{
                List<NotifySysUserView> userList = notifySysUserViewService.findByNotify(notify);
                mv.addObject("userList",userList);
            }
                mv.addObject("notify",notify);
                mv.setViewName("notifyEdit");
        }
             return mv;
    }

    /**
     *根据条件搜索的方法
     */
    @RequestMapping(value = "/search",method = RequestMethod.POST)
    @ResponseBody
    public Result search(@RequestParam(required = true, defaultValue = "1") Integer pageNum,
                         @RequestParam(required = false) Integer pageSize,
                         Notify notify){
        PageInfo<Notify> p = notifyService.findSearch(pageNum,pageSize,notify);
        if(p.getList().size()>0){
            return Result.ok(p);
        }
        return Result.error("错误");
    }


}
